package Server;

import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

import Application.WorkUnit;
import Application.WorkUnitImplementation;

public class MainServer {

	// private ArrayList<ClientHandler> clientConnections = new
	// ArrayList<ClientHandler>();
	private int port = 1337;
	private ServerSocket serverSock;
	private boolean closingDown = false;
	public ClientDispatcher clientDispatcher;

	public static void main(String[] args) throws Exception {
		new MainServer().startServer();
	}

	public MainServer() {
	}

	public MainServer(int portNumber) {
		port = portNumber;
	}

	public void startServer() {
		clientDispatcher = new ClientDispatcher();
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					System.out.println("Starting server....");
					serverSock = new ServerSocket(port);
					System.out.println("Server started!");
					while (true) {
						System.out.println("Waiting for connection");
						Socket socket = serverSock.accept();
						System.out.println("Connection Established["
								+ socket.getInetAddress() + "]: handing off...");
						clientDispatcher.addNewClient(socket);
					}
				} catch (Exception e) {
					if (!closingDown)
						System.err.println("[MainServer] Error");
				}
			}
		}).start();
	}

//	public void closeClientConnection(int clientID) {
//		// TODO [MainServer:closeClientConnection()] add code
//		for (ClientHandler clientHandler : clientConnections) {
//			if (clientHandler.getClientID() == clientID) {
//				// clientHandler.close
//			}
//		}
//	}

	public void closeServer() {
		closingDown = true;
		try {
			serverSock.close();
		} catch (Exception e) {
		}
	}

	public List<ClientHandler> getClientConnections() {
		return clientDispatcher.getClientConnections();
	}

//	public void clientDisconnected(ClientHandler clientHandler) {
//		clientConnections.remove(clientHandler);
//	}


}
